#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
RBAC数据库初始化脚本（业务逻辑驱动版本）
"""

import sys
import os
from datetime import datetime

project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, project_root)

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from src.web.core.config import get_settings
from src.web.models.rbac import Base, User, Role, Resource, Permission, UserRole
from src.web.models.rbac import UserStatus, PermissionAction, ResourceType
from src.web.auth.jwt_auth import password_manager

settings = get_settings()

def create_basic_resources(session):
    """创建基础资源 - 通过业务逻辑定义"""
    
    # 业务模块定义
    business_modules = [
        {"code": "dashboard", "name": "仪表盘", "path": "/dashboard"},
        {"code": "customers", "name": "客户管理", "path": "/customers"},
        {"code": "activities", "name": "活动管理", "path": "/activities"},
        {"code": "products", "name": "产品管理", "path": "/products"},
        {"code": "opportunities", "name": "销售机会", "path": "/opportunities"},
        {"code": "tours", "name": "出团管理", "path": "/tours"},
        {"code": "aftercare", "name": "售后服务", "path": "/aftercare"},
        {"code": "statistics", "name": "统计分析", "path": "/statistics"},
        {"code": "system", "name": "系统管理", "path": "/system"},
    ]
    
    # 动态创建资源和权限
    for module in business_modules:
        # 创建模块资源
        resource = Resource(
            name=module["name"],
            code=module["code"],
            type=ResourceType.MODULE,
            module=module["code"],
            path=module["path"],
            is_system=True
        )
        session.add(resource)
        session.flush()
        
        # 为每个模块创建标准权限
        for action in [PermissionAction.READ, PermissionAction.CREATE, 
                      PermissionAction.UPDATE, PermissionAction.DELETE]:
            permission = Permission(
                name=f"{module['name']} - {action.value}",
                code=f"{module['code']}.{action.value}",
                resource_id=resource.id,
                action=action,
                is_system=True
            )
            session.add(permission)
    
    session.commit()
    print("✅ 通过业务逻辑创建基础资源和权限")

def create_dynamic_roles(session):
    """创建角色 - 基于业务需求而非硬编码"""
    
    # 业务角色定义
    business_roles = [
        {"code": "super_admin", "name": "超级管理员", "level": 1},
        {"code": "admin", "name": "系统管理员", "level": 2},
        {"code": "manager", "name": "业务经理", "level": 3},
        {"code": "staff", "name": "业务员", "level": 4},
    ]
    
    for role_data in business_roles:
        role = Role(
            code=role_data["code"],
            name=role_data["name"],
            level=role_data["level"],
            is_system=True,
            description=f"系统默认{role_data['name']}角色"
        )
        session.add(role)
    
    session.commit()
    print("✅ 通过业务逻辑创建角色体系")

def create_test_users(session):
    """创建测试用户"""
    
    # 超级管理员
    admin_password = password_manager.hash_password("admin123")
    admin_user = User(
        username="admin",
        email="admin@example.com", 
        real_name="系统管理员",
        employee_id="EMP001",
        password_hash=admin_password,
        status=UserStatus.ACTIVE,
        is_superuser=True,
        department="系统部",
        position="超级管理员"
    )
    session.add(admin_user)
    session.flush()
    
    # 分配超级管理员角色
    super_admin_role = session.query(Role).filter(Role.code == "super_admin").first()
    if super_admin_role:
        user_role = UserRole(user_id=admin_user.id, role_id=super_admin_role.id)
        session.add(user_role)
    
    # 普通测试用户
    user_password = password_manager.hash_password("user123")
    test_user = User(
        username="user",
        email="user@example.com",
        real_name="测试用户",
        employee_id="EMP002", 
        password_hash=user_password,
        status=UserStatus.ACTIVE,
        department="销售部",
        position="销售专员"
    )
    session.add(test_user)
    session.flush()
    
    # 分配普通员工角色
    staff_role = session.query(Role).filter(Role.code == "staff").first()
    if staff_role:
        user_role = UserRole(user_id=test_user.id, role_id=staff_role.id)
        session.add(user_role)
    
    session.commit()
    print("✅ 创建测试用户账号")

def main():
    """动态RBAC初始化 - 基于业务逻辑而非硬编码"""
    print("=" * 50)
    print("CRM 动态RBAC权限管理系统初始化")
    print("基于业务逻辑，而非硬编码表关系")
    print("=" * 50)
    
    try:
        engine = create_engine(settings.DATABASE_URL.replace("+aiosqlite", ""))
        Base.metadata.create_all(engine)
        print("✅ 数据表创建完成")
        
        SessionLocal = sessionmaker(bind=engine)
        session = SessionLocal()
        
        # 1. 通过业务逻辑创建资源
        create_basic_resources(session)
        
        # 2. 通过业务需求创建角色  
        create_dynamic_roles(session)
        
        # 3. 创建测试用户
        create_test_users(session)
        
        session.close()
        
        print("\n" + "=" * 50)
        print("🎉 动态RBAC系统初始化完成！")
        print("✅ 权限关系由业务逻辑动态计算")
        print("✅ 可扩展的权限管理架构")
        print("\n登录账号:")
        print("- 管理员: admin / admin123") 
        print("- 测试用户: user / user123")
        print("=" * 50)
        
    except Exception as e:
        print(f"❌ 初始化失败: {e}")
        import traceback
        traceback.print_exc()
        return False
    
    return True

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)